package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserService;
import com.heima.utils.common.AppJwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {
    @Override
    public ResponseResult login(LoginDto dto) {
        //1.校验dto
        if(dto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2.用户名和密码 不为空  走正常校验
        if(StringUtils.isNotBlank(dto.getPhone()) && StringUtils.isNotBlank(dto.getPassword())){
            //2.1根据用户名查询db
            ApUser apUserDB = this.getOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone, dto.getPhone()));
            if(apUserDB==null){
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "手机号不存在");
            }

            //2.2用户输入的密码 + 数据库salt 加密   和数据库的password对比
            String password = dto.getPassword();//用户输入的明文密码
            String salt = apUserDB.getSalt();
            String pswd = DigestUtils.md5DigestAsHex((password + salt).getBytes());// 密码在前  盐值在后  要和注册时顺序一致

            String passwordDB = apUserDB.getPassword();
            if(StringUtils.isBlank(pswd) ||  !pswd.equals(passwordDB)){
                //密码不正确
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }


            //2.3生成jwt令牌
            String token = AppJwtUtil.getToken(apUserDB.getId().longValue());
            Map<String, Object> map = new HashMap<>();
            map.put("token", token);
            apUserDB.setPassword(null);
            apUserDB.setSalt(null);
            map.put("user", apUserDB);
            return ResponseResult.okResult(map);

        }else{
            //3.不登录先看看
            String token = AppJwtUtil.getToken(0L);
            Map<String, Object> map = new HashMap<>();
            map.put("token", token);
            return ResponseResult.okResult(map);
        }
    }
}
